package db;

import model.*;

import java.sql.*;
import java.util.ArrayList;

/**
 * DBEmployee.java
 * @author kbh
 * @version 5. oktober 2006, 2011.02.16
 *
 */
public class DBClient{
    private  Connection con;
    private DBContact dbContact = new DBContact();
    
    /** Creates a new instance of DBEmployee */
    public DBClient() {
      con = DBConnection.getInstance().getDBcon();
    }
    
  //Implements the methods from the interface
    // get all ClientGroups
    public ArrayList<Client> getAllClients(boolean _retriveAssociation)
    {
        return miscWhere("", _retriveAssociation);
    }
    //get one ClientGroup having the group type
    public Client getClientByCvr(String _cpr, boolean _retriveAssociation)
    {   String wClause = "  cvr = '" + _cpr + "'";
        return singleWhere(wClause, _retriveAssociation);
    }
    //find one ClientGroup having the id
    public Client getClientName(String _name, boolean _retriveAssociation)
    {
        String wClause = "name like '%" + _name + "%'";
        System.out.println("SearchClient " + wClause);
        return singleWhere(wClause, _retriveAssociation);
    }
    
  
     //insert a new Client group
    public int insertClient(Client _client) throws Exception
    {  
       int rc = -1;
	   String query="INSERT INTO Client(cvr, name, address, zipCode, city, phone, gsm, email, contactCPR)  VALUES('"+
		    _client.getCvr() + "', '" +
			_client.getName() + "', '" +
		    _client.getAddress() + "', '" + 
			_client.getZipCode() + "', '" +
			_client.getCity() + "', '" + 
			_client.getPhone() +  "', '" + 
			_client.getGsm() + "', '" + 
			_client.getEmail() + "', '" + 
			_client.getContact().getCpr() + "')";
                     

       System.out.println("insert : " + query);
      try{ // insert new employee +  dependent
          Statement stmt = con.createStatement();
          stmt.setQueryTimeout(5);
     	  rc = stmt.executeUpdate(query);
          stmt.close();
      }//end try
       catch(SQLException ex){
          System.out.println("Client ikke oprettet");
          throw new Exception ("Client is not inserted correctly");
       }
       return(rc);
    }

	public int updateClient(Client _client)
	{
		int rc=-1;

		String query="UPDATE Client SET "+
				"name = '" + _client.getName() + "', " +
				"address = '" + _client.getAddress() + "', " +
				"zipCode = '" + _client.getZipCode() + "', " +
				"city = '" + _client.getCity() + "', " +
				"phone = '" + _client.getPhone() + "', " +
				"gsm = '" + _client.getGsm() + "', " +
				"email = '" + _client.getEmail() + "', " +
				"contactCpr = '" + _client.getContact().getCpr() + "'" +
		          " WHERE cvr = '"+ _client.getCvr() + "'";
                System.out.println("Update query:" + query);
  		try{ // update employee
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	 	rc = stmt.executeUpdate(query);

	 	 	stmt.close();
		}//slut try
	 	catch(Exception ex){
	 	 	System.out.println("Update exception in Client db: "+ex);
	  	}
		return(rc);
	}
	
	public boolean deleteClient(String _cvr)
	{
              boolean succeeded = false;
	  
	  	String query="DELETE FROM Client WHERE cvr = '" +
				_cvr + "'";
                System.out.println(query);
	  	try{ // delete from employee
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 	  	stmt.executeUpdate(query);
	 	  	succeeded = true;
	 	  	stmt.close();
  		}//slut try	
   	        catch(Exception ex){
	 	  	System.out.println("Delete exception in Client db: "+ex);
   	        }
		return(succeeded);
	}
	
	//private methods
    //michWere is used whenever we want to select more than one employee
	
	 
	private ArrayList<Client> miscWhere(String wClause, boolean retrieveAssociation)
	{
            ResultSet results;
	    ArrayList<Client> list = new ArrayList<Client>();	
		
	    String query =  buildQuery(wClause);
  
            try{ // read the employee from the database
		Statement stmt = con.createStatement();
	 	stmt.setQueryTimeout(5);
	 	results = stmt.executeQuery(query);
	 	
	
		while( results.next() ){
	     	Client client = new Client();
		 client = buildClient(results);	
                 list.add(client);	
		}//end while
                 stmt.close();     
                 if(retrieveAssociation)
                 {   //The supervisor and department is to be build as well
                     for(Client client : list)
                     {
                        String contactCpr = client.getContact().getCpr();
                        Contact contact = dbContact.getContactCpr(contactCpr, false);
                        client.setContact(contact);
                        System.out.println("Contact is seleceted");
                     }
                 }//end if 
			
		}//slut try	
	 	catch(Exception e){
	 		System.out.println("Query exception - select: "+e);
			e.printStackTrace();
	 	}
		return list;
	}
	
	//Singelwhere is used when we only select one employee 	
	private Client singleWhere(String wClause, boolean retrieveAssociation)
	{
		ResultSet results;
		Client client = new Client();
                
	        String query =  buildQuery(wClause);
                System.out.println(query);
		try{ // read the ClientGroup from the database
	 		Statement stmt = con.createStatement();
	 		stmt.setQueryTimeout(5);
	 		results = stmt.executeQuery(query);
	 		
	 		if( results.next() ){
                            client = buildClient(results);
                            //assocaition is to be build
                            stmt.close();
                            /*if(retrieveAssociation)
                            {   //The supervisor and department is to be build as well
                                String superssn = empObj.getSupervisor().getSsn();
                                Employee superEmp = singleWhere(" ssn = '" + superssn + "'",false);
                                empObj.setSupervisor(superEmp);
                                System.out.println("Supervisor is seleceted");
                               // here the department has to be selected as well
                                int dno = empObj.getDept().getDnumber();
                                
                                Department department = dbDept.findDepartment(dno, false);
                                
                                empObj.setDepartment(department);
                                System.out.println("Department is selected");
                           
                            }*/
			}
                        else{ //no employee was found
                            client = null;
                        }
		}//end try	
	 	catch(Exception e){
	 		System.out.println("Query exception: "+e);
	 	}
		return client;
	}
	//method to build the query
	private String buildQuery(String wClause)
	{
	    String query="SELECT cvr, name, address, zipCode, city, phone, gsm, email, contactCPR  FROM Client";
		
		if (wClause.length()>0)
			query=query+" WHERE "+ wClause;
			
		return query;
	}
	//method to build an employee object
	private Client buildClient(ResultSet results)
      {   Client client = new Client();
          try{ // the columns from the table emplayee  are used
        	  	client.setCvr(results.getString("cvr"));
        	  	client.setName(results.getString("name"));
        	  	client.setAddress(results.getString("address"));
        	  	client.setZipCode(results.getString("zipCode"));
        	  	client.setCity(results.getString("city"));
        	  	client.setPhone(results.getString("phone"));
        	  	client.setGsm(results.getString("gsm"));
        	  	client.setEmail(results.getString("email"));
        	  	client.setContact(dbContact.getContactCpr(results.getString("contactCpr"), false));
          }
         catch(Exception e)
         {
             System.out.println("error in building the Client object");
         }
         return client;
      }

 
}  
    

